<?php
/*IWA project - ajax.php
Maximilian Einoeder
Mark Mensing
 */

include 'RARAR.php';

//Get information
$from = $_POST['From'];
$to = $_POST['To'];
$date = $_POST['Date'];
//$time = $_POST['Hour'].':'.$_POST['Minute'];
$time = $_POST['Time'];


print $test;
$test = 'x';
//Create a rarar instance, since we can't use the one on the result page
$myrarar = new RARAR($from,$to, $date, $time);


$filters = $_POST['filters'];

//Filter the POI's again
$trainStops = $myrarar->getTrainconnection();
$railresult = $myrarar->get_railresult($trainStops, $filters);

$roadresult = $myrarar->get_result($filters);

//Get which function has to be done
$function = $_POST['function'];

if($function == 'filter') {
    try {
    /*Get the filters to use*/
    $filters = $_POST['filters'];
    
    //Filter the POI's again
    $trainStops = $myrarar->getTrainconnection();
    $railresult = $myrarar->get_railresult($trainStops, $filters);
    
    $roadresult = $myrarar->get_result($filters);
    
    /* Create a 2d array with train POI's
     * x[0] = POI name
     * x[1] = POI distance
     * x[2] = Station to leave from
     * x[3] = feature code
     * x[4] = POI lat
     * x[5] = POI long
     * x[6] = closest station lat
     * x[7] = closest station long
     * x[8] = closest station name
     */
    
    $outputTrain = array();
    
    foreach($railresult as $key=>$r) {
        $coordinates= $myrarar->getStationLatLong($r['beststation']);
        $outputTrain[] = array($r['name'], rawurlencode(round($r['moreway'], 1)), $trainStops[$r['beststation']][0], $r['fcode'], $r['lat'], $r['lng'], $coordinates[0], $coordinates[1], $coordinates[2]);
    }
    
    /* Create a 2d array with train POI's
     * x[0] = POI name
     * x[1] = POI distance
     * x[2] = feature code
     * x[3] = POI lat
     * x[4] = POI long
     */
    $outputCar = array();
    
    foreach($roadresult as $key=>$r) {
        $outputCar[] = array($r['name'], round(($r['length']/1000),1), $r['fcode'], $r['lat'], $r['lng']);
    }
    
    //Create a 3-d array
    $output = array($outputCar, $outputTrain);
    
    echo json_encode($output);
    } catch(Exception $e) {
        echo 'error';
    }
}
else if($function == 'getStation') {
    
    
    if(isset($myrarar)) {
        echo json_encode($myrarar->getStationLatLong($_POST['stationName']));
    }
}
?>
